package com.jaryle.quartz.util;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component;

/**
 * 描述:
 * 任务工厂
 * 继承org.springframework.scheduling.quartz.SpringBeanJobFactory
 * 实现任务实例化方式
 *
 * @author jaryle
 * @version V1.0
 * @create 2018-11-28
 */
@Component
public class SpringJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
    @Autowired
    private AutowireCapableBeanFactory BeanFactory;
    /**
     * Job默认由Quartz管理，如果需要使用Spring容器管理bean，也就是依赖注入，需要指定JobFactory，也就是指定将Job由Spring容器管理。
     * @param applicationContext
     * @throws BeansException
     */

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.BeanFactory = applicationContext.getAutowireCapableBeanFactory();
    }
    /**
     * 将job实例交给spring ioc托管
     * 我们在job实例实现类内可以直接使用spring注入的调用被spring ioc管理的实例
     * @param bundle
     * @return
     * @throws Exception
     */
    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
         Object jobbean = super.createJobInstance(bundle);
         //将jobbean实例交付给spring ioc
         BeanFactory.autowireBean(jobbean);
         return jobbean;
    }
}
